﻿//using System;
//using System.IO;
//using System.Net;
//using System.Threading;

//namespace Marc.JwOrgClient {
//    public class PodcastDownloader {
//        private readonly Podcast _podcast;

//        public PodcastDownloader(Podcast podcast) {
//            _podcast = podcast;
//        }

//        public void SyncWithLocalDirectory(IPodcastNamingStrategy strategy, string path) {
//            var nextDownloadCanStart = new AutoResetEvent(true);

//            foreach (PodcastMagazine magazine in _podcast.Magazines) {
//                string magazineDirectoryPath = strategy.GetDirectoryPath(magazine);
//                if (!Directory.Exists(magazineDirectoryPath)) {
//                    Directory.CreateDirectory(magazineDirectoryPath);
//                }
//                foreach (PodcastMagazineChapter magazineChapter in magazine.Chapters) {
//                    PodcastMagazineChapter chapter = magazineChapter;
//                    string fileName = strategy.GetFileName(magazine, chapter);
//                    if (!File.Exists(fileName)) {
//                        nextDownloadCanStart.WaitOne();
//                        WebRequest request = WebRequest.Create(magazineChapter.Link);
//                        request.BeginGetResponse(
//                            ar => {
//                                if (ar.IsCompleted) {
//                                    using (WebResponse response = request.EndGetResponse(ar)) {
//                                        using (Stream responseStream = response.GetResponseStream()) {
//                                            if (responseStream == null) {
//                                                throw new InvalidOperationException(string.Format("Download from {0} failed", chapter.Link));
//                                            }
//                                            using (FileStream fStream = File.Create(Path.Combine(magazineDirectoryPath, fileName))) {
//                                                responseStream.CopyTo(fStream);
//                                            }
//                                        }
//                                    }
//                                }
//                                nextDownloadCanStart.Set();
//                            }, null);
//                    }
//                }
//            }
//        }
//    }
//}